package com.yswl.pri.picture;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yswl.pri.R;
import com.yswl.pri.common.ToolbarMFragment;
import com.yswl.pri.eventbus.PictureDialogEvent;
import com.yswl.pri.picture.entry.FuliBean;
import com.yswl.pri.picture.entry.ImageBean;
import com.yswl.pri.picture.entry.ImageSourceCategory;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import yswl.com.klibrary.MApplication;
import yswl.com.klibrary.base.BaseRecyclerAdapter;
import yswl.com.klibrary.base.BaseViewHolder;
import yswl.com.klibrary.http.CallBack.HttpCallback;
import yswl.com.klibrary.http.HttpClientProxy;
import yswl.com.klibrary.http.okhttp.MDeviceUtil;
import yswl.com.klibrary.util.L;
import yswl.com.klibrary.util.MUrlUtil;

public class PictureList2Fragment extends ToolbarMFragment implements HttpCallback<JSONObject> {
    private static final String TAG = PictureList2Fragment.class.getSimpleName();
    private static final int LOAD_MORE = 1;
    private static final int REFRESH = 2;
    private static final String ARG_PARAM1 = "param1";

    private ImageSourceCategory mParam1;
    private int currPage = 0;

    public static PictureList2Fragment newInstance(ImageSourceCategory param1) {
        PictureList2Fragment fragment = new PictureList2Fragment();
        Bundle args = new Bundle();
        args.putSerializable(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = (ImageSourceCategory) getArguments().getSerializable(ARG_PARAM1);
        }
    }

    ImagsListAdapter2 mAdapter;
    RefreshLayout refreshLayout;
    PictureDialog dialogFrg;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_pic_list, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        //initUI
        refreshLayout = view.findViewById(R.id.refreshLayout);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                loadData(REFRESH);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                loadData(LOAD_MORE);
            }
        });
        RecyclerView recyclerView = view.findViewById(R.id.recyclerview);
        int spanCount = 2;
        if (MDeviceUtil.isTvOrMoble(getMActivity())) {
            spanCount = 4;
        }
        GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), spanCount);
        recyclerView.setLayoutManager(layoutManager);
        SpacesItemDecoration decoration = new SpacesItemDecoration(5);
        recyclerView.addItemDecoration(decoration);
        mAdapter = new ImagsListAdapter2(getActivity(), null, R.layout.adapter_image_gride_item);
        mAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(final int position) {
                MApplication.getApplication().getGolbalHander().post(new Runnable() {
                    @Override
                    public void run() {
                        if (dialogFrg == null)
                            dialogFrg = PictureDialog.getInstance();
                        dialogFrg.show(getChildFragmentManager(), "xiimage");
                        PictureDialogEvent.postEvent(defultImagBean, position);
                    }
                });
            }
        });
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mAdapter);
        refreshLayout.autoRefresh();
    }


    List<ImageBean> defultImagBean = new ArrayList<>();

    List<ImageBean> copyImageData() {
        List<FuliBean> baiduImageBeans = mAdapter.getList();
        if (baiduImageBeans == null) return null;
        List<ImageBean> imageBeans = new ArrayList<>();
        for (int i = 0; i < baiduImageBeans.size(); i++) {
            FuliBean currBai = baiduImageBeans.get(i);
            ImageBean currIma = new ImageBean();
            currIma.image_url = currBai.getUrl();
            imageBeans.add(currIma);
        }
        return imageBeans;
    }

    private void loadData(int Mode) {
        if (Mode == LOAD_MORE) currPage++;
        if (Mode == REFRESH) currPage = 1;
        String url = null;
        if (mParam1 == ImageSourceCategory.FULI) {
            url = MUrlUtil.getUrl(this, R.string.url_fuli2, currPage, 10);
        }
        HttpClientProxy.getInstance().getAsyn(url, Mode, null, this);
    }

    @Deprecated
    int getRondom() {
        final double r = Math.random();
        final int rd = (int) (r * 10);
        return rd;
    }

    ArrayList<FuliBean> mImagesF;

    @Override
    public void onSucceed(int requestId, JSONObject result) {
        L.d(TAG, " onSucceed : " + result);
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        if (result == null) return;
        if (mParam1 == ImageSourceCategory.FULI) {
            boolean ok = result.optBoolean("error");
            if (!ok) {
                mImagesF = FuliBean.jsonToList(result);
                if (requestId == REFRESH) {
                    mAdapter.setList(mImagesF);
                } else {
                    mAdapter.addList(mImagesF);
                }
                defultImagBean = copyImageData();
            }

        }


    }

    @Override
    public void onFail(int requestId, String errorMsg) {
        L.e(TAG, " onFail : " + errorMsg);
        refreshLayout.finishRefresh(false);
        refreshLayout.finishLoadMore(100, false, false);//传入false表示加载失败
    }

    public class ImagsListAdapter2 extends BaseRecyclerAdapter<FuliBean> {

        public ImagsListAdapter2(Context mContext, List<FuliBean> mList, int itemLayoutId) {
            super(mContext, mList, itemLayoutId);
        }

        @Override
        public void onBind(BaseViewHolder holder, FuliBean imag, int position) {
            ImageView imageView = holder.findById(R.id.image);
            Glide.with(mContext).asBitmap()
                    .load(imag.getUrl()).thumbnail(0.01f)
                    .into(imageView);
        }
    }
}
